"""Minute grouper class."""

import datetime as dt

import system.navalasystem as na
import parts
from system import configs as con
import misc
import timedata
import quoteperiod as qp

class MinuteGrouper(parts.Stocker):
    """Records min5, ... min60 quotes based on min1 quotes."""
    
    ## Setup
    # =[qp.secondly]+range(qp.min3, qp.daily)
#    periods = [qp.secondly]+range(qp.min3, qp.daily)
    periods = range(qp.min3, qp.daily)
    
    def __init__(self):
        self.logger = misc.GetLogger(name="minutegrouper")
        
    def GroupQuotes(self):
        """Secondly is included."""
        ts2 = misc.EndOfDay(dt.datetime.today())
        for period in self.periods:
            if period == qp.secondly:
                ts1 = misc.BeginningOfDay(dt.datetime.today())
                self.logger.info("=== Period ``%s`` ===" % qp.data[period]["english"])
            for name in self._allNames: # name is stock name
                self.logger.debug("= Stock ``%s`` =" % name)
                if period != qp.secondly:
                    ts1 = na.vala.db.quote_GetMaxHistTimestamp(period, name)
                    if ts1 is None:
                        ts1 = qp.data[period]["start"]
#                self.logger.debug("Period is %s -- %s" % (misc.ts2dt(ts1), misc.ts2dt(ts2)))
                Q = na.vala.db.quote_GetData(
                    qp.min1, name, ts1, ts2)
                if len(Q) == 0:
                    self.logger.debug("No quotes")
                    continue
                if period != qp.secondly:
                    Q2 = timedata.GroupQuotes(Q, qp.data[period]["nm"])
#                    self.logger.debug("%d ---> %d quotes" % (len(Q), len(Q2)))
                    na.vala.db.quote_Record(period, name, Q2)
                else:
                    na.vala.db.quote_Record(period, name, Q, True)
#                    self.logger.debug("%d quotes into secondly" % len(Q))
#        self.logger.debug("================= FINISHED!")
###        
###    def TransferToSecondly(self):
###        """Records into the secondly table with flagRSAN=True (see database.py)."""
###        ts2 = misc.EndOfDay(dt.datetime.today())
###        for name in self._allNames: # name is stock name
###            self.logger.debug("= Stock ``%s`` =" % name)
###            ts1 = na.vala.db.quote_GetMaxHistTimestamp(period, name)
###            if ts1 is None:
###                ts1 = qp.data[period]["start"]
###            self.logger.debug("Period is %s -- %s" % (misc.ts2dt(ts1), misc.ts2dt(ts2)))
###            Q = na.vala.db.quote_GetData(
###                qp.min1, name, ts1, ts2)
###            if len(Q) == 0:
###                self.logger.debug("No quotes")
###                continue
###            Q2 = timedata.GroupQuotes(Q, qp.data[period]["nm"])
###            self.logger.debug("%d ---> %d quotes" % (len(Q), len(Q2)))
###            na.vala.db.quote_Record(period, name, Q2)
###    
